<?php
	require_once($_SERVER["DOCUMENT_ROOT"]."/alerter/modules/base_mod.php");
//	require_once($_SERVER["DOCUMENT_ROOT"]."/alerter/modules/settings_mod.php");
//	require_once($_SERVER["DOCUMENT_ROOT"]."/alerter/modules/security_mod.php");
	require_once($_SERVER["DOCUMENT_ROOT"]."/alerter/modules/alert_mod.php");

	$tickHour = gmdate ("H");
//echo ("GMT Hour:".$tickHour."<br>");
	if ($tickHour != "01" && $tickHour != "07" && $tickHour != "13" && $tickHour != "19") {
		return;
	}
//echo ("Timestamp: " . gmmktime () . " - " . gmdate("M d Y H:i:s") . "<br>");

	$sql_stock = "SELECT tile_id,data FROM flog_stock WHERE tile_id IN (";
//echo ("10 Updating MOs<br>");
	
	// Read the flog_facility to get the MOs' tile_ids and construct the SQL query for the Stock table
	$conn = AlertBaseMod::getConnection();
	$sql = "SELECT tile_id FROM `flog_facility` WHERE MATCH (data) AGAINST ('\"Military Outpost\"' IN BOOLEAN MODE)";
	$rows = mysql_query($sql, $conn);
	$first = true;
	while ($row = mysql_fetch_assoc($rows)) {
		if ($first) {
			$first = false;
		} else {
			$sql_stock = $sql_stock . ",";
		}
		$sql_stock = $sql_stock . $row["tile_id"];
	}
	$sql_stock = $sql_stock . ")";
//echo ("Query: " . $sql_stock . "<br>");
	
	// Now read the stock information, decode it, decrease the stock amount for every building and save it back
	$update = array();
	$conn = AlertBaseMod::getConnection();
	$rows = mysql_query($sql_stock, $conn);
	while ($row = mysql_fetch_assoc($rows)) {
//echo ("Checking: " . $row["tile_id"] . " Data: " . $row["data"] . "<br>");
		$data = json_decode ($row["data"], true);
		$stock = $data["stock"];
		if ($stock["2"][1] >= 5 && $stock["16"][1] >= 5) {
//echo ("Ticking.<br>");
//echo ("Old values: E:".$stock["2"][1]." F:".$stock["16"][1]."<br>");
			// Check if there's eough upkeepfor this tick.
			$stock["2"][1] -= 5;
			$stock["16"][1] -= 5;
			$data["stock"] = $stock;
//echo ("Timestamp: " . gmmktime () . " - " . gmdate("M d Y H:i:s") . "<br>");
			$data["last_tick"] = gmmktime ();
//echo ("New values: E:".$data["stock"]["2"][1]." F:".$data["stock"]["16"][1]."<br>");
			$data["space"] += 10;
			$new = json_encode ($data);
			$update[$row["tile_id"]] = $new;
		}
	}
//echo ("Checking done.<br>Updating<br>");
	$conn = AlertBaseMod::getConnection();
	$timestamp = gmmktime ();
	foreach ($update as $tileId => $data) {
		$sql = sprintf ("UPDATE flog_stock SET data=%s,timestamp=%d WHERE tile_id=%d", "'".$data."'", $timestamp, $tileId);
//echo ($sql . "<br>");
		mysql_query($sql, $conn);
	}
	
//echo ("Done<br>End.<br>");
	
	//$message = "MO AutoTick on ".gmdate("M d Y H:i:s")."\n\n";
	//$to = "jirina42@seznam.cz";
	//$subject = "MO AutoTick";
	//$from = "mo.autotick@mo.com";
	//$headers = "From:" . $from;
	//mail($to,$subject,$message,$headers);
	//echo "Mail Sent.";
?>